<template>
  <div class="sc-design-sm">
    <q-card class="my-card" style="margin: 0 12px; padding: 0 50px">
      <div class="row items-center" style="width: 100%">
        <div style="width: 100%">
          <q-card-section class="col-sm-9 col-xs-8 q-px-none">
            <div
              class="row q-gutter-y-sm q-gutter-x-md justify-end"
              style="
                justify-content: space-between;
                width: 100%;
                align-items: center;
              "
            >
              <div class="bg-white q-pa-md">
                <div class="text-h6"><strong>产品列表</strong></div>
              </div>
              <div class="col-md-3 col-xs-12" style="max-width: 280px">
                <q-input
                  ref="ruleName"
                  placeholder="请输入搜索内容"
                  outlined
                  v-model="listQueryData.matter"
                  dense
                  @keydown.enter="queryData"
                  square
                >
                  <template v-slot:append>
                    <q-btn
                      style="
                        margin-right: -12px;
                        width: 40px;
                        height: 100%;
                        background-color: #1890ff;
                      "
                      class="no-border-radius"
                      text-color="white"
                      dense
                      padding="xs"
                      flat
                      color="lightgrey"
                      icon="search"
                      @click="queryData"
                    ></q-btn>
                  </template>
                </q-input>
              </div>
              <div class="col-md-auto col-xs-12 q-pb-sm col-sm gt-sm">
                <q-btn
                  :ripple="false"
                  dense
                  flat
                  style="background: #1890ff; color: white; padding: 0 15px"
                  unelevated
                  icon="add"
                  class="no-border-radius q-px-sm"
                  label="添加产品"
                  @click="addTaskDialog"
                />
              </div>
            </div>
          </q-card-section>
        </div>
      </div>
    </q-card>
    <div class="q-mx-sm q-mt-sm q-pb-md text-grey-8 text-center">
      <sc-page
        :items="goodsListData"
        :datacounts="total"
        :perNumber="pageSize"
        @ChangeCurrentPage="getChangeCurrentPage"
        @ChangeInputPagePage="getChangeInputPagePage"
        item-class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12"
      >
        <template v-slot:item="props">
          <q-intersection once transition="scale">
            <sc-shadow style="padding-bottom: 0px">
              <q-card class="my-card">
                <q-card-section style="padding: 10px 5px">
                  <q-item-label
                    class="text-bold"
                    style="
                      padding: 10px 20px;
                      text-align: left;
                      font-size: 14px;
                      color: #333;
                    "
                    >{{ props.item.title }}</q-item-label
                  >
                  <q-img
                    :src="props.item.inforimg.split(',')[0]"
                    :ratio="4 / 3"
                    class="q-mt-md"
                    style="width: 85%"
                  />
                  <q-card-section style="padding: 0px">
                    <q-item-label
                      class="row text-body2 text-grey-7 q-gutter-x-xs q-pl-xs q-pt-lg"
                      style="padding: 0px"
                    >
                      <span
                        class="col-auto col-xs-12"
                        style="
                          border-top: 1px solid #ccc;
                          text-align: center;
                          padding: 10px 20px 0 20px;
                          margin-top: 10px;
                          font-size: 14px;
                        "
                        >上传日期：{{ props.item.releasedate }}</span
                      >
                      <div class="EDcenter">
                        <q-btn-group flat>
                          <q-btn
                            flat
                            dense
                            icon="edit"
                            size="md"
                            color="grey-6"
                            class="q-mr-md"
                            @click="editItem(props.item)"
                          >
                            <q-tooltip>编辑</q-tooltip>
                          </q-btn>
                          <q-separator vertical inset="" />
                          <q-btn
                            flat
                            dense
                            icon="delete_forever"
                            size="md"
                            color="red"
                            class="q-mx-md"
                            @click="deleteItem(props.item)"
                          >
                            <q-tooltip>删除</q-tooltip>
                          </q-btn>
                        </q-btn-group>
                      </div>
                    </q-item-label>
                  </q-card-section>
                </q-card-section>
              </q-card>
            </sc-shadow>
          </q-intersection>
        </template>
      </sc-page>
    </div>
    <q-dialog
      v-model="addTask"
      fullscreen
      @escape-key="diahide"
      @hide="diahide"
      no-backdrop-dismiss
    >
      <q-card style="width: 60%; max-width: inherit" square class="q-pb-md">
        <q-card-section
          class="row items-center"
          style="background-color: #1890ff; color: #fff; padding-left: 40px"
        >
          <div class="text-h6">{{ task_title }}</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <form
          ref="addDataForm"
          @submit.prevent.stop="onSubmit"
          @reset.prevent.stop="onReset"
        >
          <q-card-section class="row justify-center">
            <div class="col-sm-12 col-xs-12 q-gutter-md">
              <q-input
                class="q-pb-none"
                ref="title"
                placeholder="请输入标题"
                outlined
                v-model="waitEdit.title"
                dense
                square
                clearable
                :rules="[
                  (val) => (val && val.length > 3) || '请输入标题并大于3个字符'
                ]"
              >
                <template v-slot:before>
                  <div class="text_name">标题</div>
                </template>
              </q-input>
              <q-toggle
                v-model="isdatatype"
                size="lg"
                :icon="isdataicon"
                @input="changedata"
                label="选择发布文章/视频"
                v-show="task_title == '添加'"
              />
              <q-input
                class="q-pb-none"
                placeholder="请输入文章链接"
                outlined
                v-model="waitEdit.dataurl"
                dense
                square
                clearable
                v-if="!isdatatype"
              >
                <template v-slot:before>
                  <div class="text_name">文章链接</div>
                </template>
              </q-input>
              <q-input
                class="q-pb-none"
                placeholder="请输入视频链接"
                outlined
                v-model="waitEdit.videourl"
                dense
                square
                clearable
                v-else
              >
                <template v-slot:before>
                  <div class="text_name">视频链接</div>
                </template>
              </q-input>
              <q-select
                class="q-pb-none q-pt-sm"
                outlined
                v-model="waitEdit.infortype"
                :options="options"
                placeholder="请选择"
                ref="infortype"
                dense
                square
                clearable
                style="margin-bottom: 22px"
                :rules="[(val) => (val && val.length > 0) || '请选择资讯类型']"
              >
                <template v-slot:before>
                  <div class="text_name">产品类型</div>
                </template>
              </q-select>
              <div class="col-12 row q-mb-md">产品内容</div>
              <input
                type="file"
                style="display: none"
                class="editorFile"
                accept="image/*"
                @change="handleFile_editor"
              />
              <q-editor
                v-model="qeditor"
                :dense="$q.screen.lt.md"
                :definitions="{
                  upload: {
                    tip: '上传图片',
                    icon: 'cloud_upload',
                    label: '上传',
                    handler: uploadIt
                  }
                }"
                :toolbar="[
                  [
                    {
                      label: '排列',
                      icon: $q.iconSet.editor.align,
                      fixedLabel: true,
                      list: 'only-icons',
                      options: ['left', 'center', 'right', 'justify']
                    }
                  ],

                  [
                    'bold',
                    'italic',
                    'strike',
                    'underline',
                    'subscript',
                    'superscript'
                  ],
                  ['token', 'hr', 'link', 'custom_btn'],
                  ['print', 'fullscreen'],
                  [
                    {
                      label: $q.lang.editor.formatting,
                      icon: $q.iconSet.editor.formatting,
                      list: 'no-icons',
                      options: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'code']
                    },
                    {
                      label: ' 字体大小',
                      icon: $q.iconSet.editor.fontSize,
                      fixedLabel: true,
                      fixedIcon: true,
                      list: 'no-icons',
                      options: [
                        'size-1',
                        'size-2',
                        'size-3',
                        'size-4',
                        'size-5',
                        'size-6',
                        'size-7'
                      ]
                    },
                    {
                      label: '默认字体',
                      icon: $q.iconSet.editor.font,
                      fixedIcon: true,
                      list: 'no-icons',
                      options: [
                        'default_font',
                        'arial',
                        'arial_black',
                        'comic_sans',
                        'courier_new',
                        'impact',
                        'lucida_grande',
                        'times_new_roman',
                        'verdana'
                      ]
                    },
                    'removeFormat'
                  ],
                  ['quote', 'unordered', 'ordered', 'outdent', 'indent'],
                  ['upload'],
                  ['undo', 'redo'],
                  ['viewsource']
                ]"
                :fonts="{
                  arial: 'Arial',
                  arial_black: 'Arial Black',
                  comic_sans: 'Comic Sans MS',
                  courier_new: 'Courier New',
                  impact: 'Impact',
                  lucida_grande: 'Lucida Grande',
                  times_new_roman: 'Times New Roman',
                  verdana: 'Verdana'
                }"
                style="min-height: 26rem"
              />
              <div class="col-12 row q-mb-md">封面图</div>
              <div class="col-12 row flexRow">
                <el-upload
                  class="upload-demo"
                  :action="
                    upload_url +
                    '?guestcode=' +
                    waitEdit.guestcode +
                    '&imgpjid=' +
                    waitEdit.pjid
                  "
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :file-list="fileList"
                  list-type="picture-card"
                  :limit="9"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </div>
              <!-- <div slot="tip" class="el-upload__tip">
                <el-button type="primary" id="NewButton">点击上传</el-button>
                只能上传jpg/png文件，最多允许添加9张图片，建议图片比例：<span
                  >1:1</span
                >
              </div> -->
              <div class="text-right">
                <q-btn
                  outline
                  unelevated
                  label="取消"
                  v-close-popup
                  type="reset"
                  class="q-mr-sm no-border-radius"
                  color="grey-6"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="发布"
                  color="primary"
                  class="no-border-radius"
                  v-if="isEdit == '0'"
                  :loading="loginLoading"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="保存"
                  color="primary"
                  class="no-border-radius"
                  :loading="loginLoading"
                  v-else
                />
              </div>
            </div>
          </q-card-section>
        </form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import ScShadow from 'components/shadow/ScShadow'
import ScPage from 'components/common/ScPage'
import { getLoginData } from '@/utils/localStorage'
import {
  GetDefaultlistApi,
  delimgApi,
  ReleasedataApi,
  Op_inforApi,
  RemoveInews
} from '@/api/cardApi'
import { baseUrl, imgUrl, proUrl } from '@/utils/config'
export default {
  name: 'proList',
  components: {
    ScPage,
    ScShadow
  },
  data() {
    return {
      page: 1,
      pageSize: 12,
      total: 0,
      sort: '',
      keyword: '',
      listQueryData: {
        matter: ''
      },
      infortype: '全部',
      options: ['产品信息'],
      goodsListData: [],
      userInfo: {},
      waitEdit: {},
      loginLoading: false,
      isEdit: '',
      fileList: [],
      msg: '上传',
      upload_url: proUrl + '/api/InheartApi/uploadimg',
      imgfileList: [],
      qeditor: '',
      isdatatype: false,
      task_title: '添加',
      isdataicon: 'article',
      addTask: false,
      pjid: '',
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {},
  methods: {
    getChangeCurrentPage(val) {
      this.getdatalist(val)
    },
    getChangeInputPagePage(val) {
      this.getdatalist(val)
    },
    getdatalist(pageindex) {
      let that = this
      let guestcode = that.userInfo.reguserno
      let gscode = that.userInfo.gscode
      let data = {}
      data = {
        guestcode: guestcode,
        gscode: gscode,
        pageindex: pageindex,
        pagesize: that.pageSize,
        stype: that.stype,
        sort: that.sort,
        keyword: that.keyword,
        stype: '产品信息'
      }
      GetDefaultlistApi(data).then((res) => {
        if (res.code == 0 && res.data.length > 0) {
          that.goodsListData = res.data
          that.total = res.dataCount
        } else {
          that.goodsListData = []
        }
      })
    },
    queryData() {
      let that = this
      const listQueryData = this.listQueryData
      that.keyword = listQueryData.matter
      that.getdatalist(1)
    },
    diahide() {
      let that = this
      that.getdatalist(1)
    },
    //文本编辑器上传图片
    uploadIt() {
      this.EditorFileUpload()
    },
    EditorFileUpload() {
      document.getElementsByClassName('editorFile')[0].click()
    },
    AdvimgUpload() {
      document.getElementsByClassName('advFile')[0].click()
    },
    isMatchData(data) {
      const listQueryData = this.listQueryData
      let matterFlag = false
      if (
        !listQueryData.matter ||
        data.matter.search(listQueryData.matter) !== -1
      ) {
        matterFlag = true
      }
      let matterStateFlag = false
      if (
        listQueryData.matterState === '全部' ||
        data.state === listQueryData.matterState
      ) {
        matterStateFlag = true
      }
      return matterFlag && matterStateFlag
    },
    // 文本编辑器上传图片
    handleFile_editor: function (e) {
      const $target = e.target
      const file = $target.files[0]
      const reader = new FileReader()
      reader.readAsDataURL(file)
      this.headFile = file
      const formData = new FormData()
      formData.append('file', this.headFile)
      //console.log(formData, file)
      e.target.value = ''
      uploadimg(formData).then((res) => {
        if (res.code == '0') {
          commonUtil.notifySuccess('上传成功')
          let urlImg = res.url
          let url = imgUrl + urlImg + '&original=1'
          let shtml = '<img style="max-width:100%" src="' + url + '"/>'
          this.qeditor = this.qeditor + shtml
        } else {
          commonUtil.notifyError(res)
        }
      })
    },
    //上传
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      let that = this
      // let data_imgUrl = ''
      let url
      if (file.response) {
        url = file.response.url + file.response.data
      } else {
        url = file.url
      }
      if (url.substring(0, 5) == 'blob:') {
        return
        //    that.$q.notify({
        //       color: 'white',
        //       textColor: 'positive',
        //       type: 'negative',
        //       position: 'top',
        //       message: '删除失败'
        // })
      }

      // var index = that.imgfileList.indexOf(url)
      // that.imgfileList.splice(index, 1)
      // that.imgfileList.forEach((element) => {
      //   data_imgUrl +=
      //     element.replace(imgUrl, '').replace('&original=1', '') + ','
      // })
      const index = this.fileList.findIndex((item) => item.url === url)
      if (index !== -1) {
        this.fileList.splice(index, 1)
      }
      delimgApi({
        guestcode: that.waitEdit.guestcode,
        imgurl: url
      }).then((res) => {
        if (res.code == '0') {
          that.$q.notify({
            color: 'white',
            textColor: 'positive',
            icon: 'check_circle',
            position: 'top',
            message: '删除成功'
          })
        }
      })
    },
    changedata() {
      let that = this
      if (that.isdatatype) {
        that.isdataicon = 'video_library'
      } else {
        that.isdataicon = 'article'
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      this.$q.notify({
        color: 'white',
        textColor: 'positive',
        icon: 'check_circle',
        position: 'top',
        message: '上传成功'
      })
      let old = this.waitEdit.inforimg
      if (this.waitEdit.inforimg) {
        this.waitEdit.inforimg = old + ',' + res.url + res.data
      } else {
        this.waitEdit.inforimg = res.url + res.data
      }
      // console.log(res, file);
    },
    //添加按钮
    addTaskDialog() {
      this.fileList = []
      // this.msg = '点击上传'
      // setTimeout(() => {
      //   const smallButton = document.getElementById('OldButton')
      //   const primaryButton = document.querySelector('#NewButton')
      //   smallButton.style.display = 'none'
      //   primaryButton.addEventListener('click', () => {
      //     smallButton.click()
      //   })
      // }, 500)
      this.isEdit = '0'
      this.waitEdit = {}
      this.addTask = true
      this.qeditor = ''
      this.task_title = '添加'
      this.imgfileList = []
      this.getCurrentTime()
      this.waitEdit.guestcode = this.userInfo.reguserno
      this.waitEdit.pjid = this.pjid
      // console.log(this.pjid,this.waitEdit.pjid);
    },
    // 编辑
    editItem(item) {
      this.isEdit = '1'
      this.addTask = true
      // this.msg = '点击上传'
      // setTimeout(() => {
      //   const smallButton = document.getElementById('OldButton')
      //   const primaryButton = document.querySelector('#NewButton')
      //   smallButton.style.display = 'none'
      //   //console.log(primaryButton)
      //   primaryButton.addEventListener('click', () => {
      //     smallButton.click()
      //   })
      // }, 500)
      this.waitEdit = _.clone(item)
      this.qeditor = item.body
      this.task_title = '编辑产品'
      this.imgfileList = []
      if (this.waitEdit.inforimg != '' && this.waitEdit.inforimg != undefined) {
        for (var j = 0; j < this.waitEdit.inforimg.split(',').length; j++) {
          this.imgfileList.push(this.waitEdit.inforimg.split(',')[j])
        }
      }
      this.fileList = this.waitEdit.inforimg.split(',').map((url, index) => ({
        name: `food${index + 1}.jpeg`,
        url: url
      }))
    },
    //删除
    deleteItem(item) {
      let that = this
      that.waitEdit = _.clone(item)
      const addModel = _.clone(that.waitEdit)
      addModel.guestcode = that.userInfo.reguserno
      addModel.gscode = that.userInfo.gscode
      addModel.sType = 'Delete'
      that.$q
        .dialog({
          title: '提示',
          message: '是否确认删除?',
          cancel: {
            'text-color': 'black',
            color: 'white',
            label: '取消'
          },
          ok: {
            label: '确定'
          },
          persistent: true
        })
        .onOk(() => {
          RemoveInews(addModel).then((res) => {
            if ((res.code = '0')) {
              that.$q.notify({
                color: 'white',
                textColor: 'positive',
                icon: 'check_circle',
                position: 'top',
                message: '删除成功'
              })
              that.getdatalist(1)
            }
          })
        })
        .onCancel(() => {})
    },
    getCurrentTime() {
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      let ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      var code = ''
      var codeLength = 6
      var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
      for (var i = 0; i < codeLength; i++) {
        var index = Math.floor(Math.random() * 9)
        code += random[index]
      }
      this.pjid = yy + mm + dd + hh + mf + ss + code
    },
    onReset() {
      this.waitEdit.title = null
      this.waitEdit.desc = null
      this.waitEdit.id = null
      this.waitEdit.state = null
      this.waitEdit.inforimg = undefined
    },
    onSubmit() {
      let that = this
      that.loginLoading = true
      let addModel = {}
      if (that.isEdit == '0') {
        addModel.guestcode = that.userInfo.reguserno
        addModel.gscode = that.userInfo.gscode
        addModel.title = that.waitEdit.title ?? ''
        addModel.infortype = that.waitEdit.infortype ?? ''
        addModel.body = that.qeditor
        addModel.author = that.userInfo.userName
        addModel.dataurl = that.dataurl ?? ''
        addModel.videourl = that.videourl ?? ''
        addModel.imgpjid = that.pjid ?? ''
        ReleasedataApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '发布成功'
            })
            setTimeout(() => {
              that.getdatalist(1)
              that.loginLoading = false
              that.addTask = false
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      } else {
        addModel = _.clone(that.waitEdit)
        //资讯信息
        addModel.title = that.waitEdit.title
        addModel.body = that.qeditor
        addModel.infortype = that.waitEdit.infortype
        addModel.dataurl = that.dataurl ?? ''
        addModel.videourl = that.videourl ?? ''
        addModel.inforimg = that.inforimg ?? ''
        //日志信息
        addModel.op_type = 'edit'
        addModel.username = that.userInfo.userName
        addModel.headimg = that.userInfo.headerImg
        addModel.openid = that.userInfo.openid ?? ''
        addModel.id = that.waitEdit.id
        addModel.inforimg = that.waitEdit.inforimg ?? ''
        Op_inforApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '修改成功'
            })
            setTimeout(() => {
              that.loginLoading = false
              that.addTask = false
              that.getdatalist(1)
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      }
    }
  },
  mounted() {
    const user = getLoginData()
    if (user == null) {
      this.$router.push('/user/login')
      return
    }
    this.userInfo = user
    this.getdatalist(1)
  }
}
</script>

<style scoped lang="scss">
.example-item {
  height: 289px;
  width: 100%;
}
.q-mt-md {
  margin-top: 0px !important;
}
::v-deep .text-center > div > div > .col-xl-2 {
  width: 20% !important;
}
#OldButton {
  display: none;
}
:deep(.el-upload-list__item-name) {
  display: none !important;
}
#NewButton {
  width: 200px;
}
:deep(.el-upload-list--picture .el-upload-list__item-thumbnail) {
  width: 250px;
  height: 180px;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  width: auto;
  // display: inline;
  // line-height: 24px;
  // height: auto;
  // word-break: break-all;
  // word-wrap: break-word;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  border: 0;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  // margin-right: 10px;
  height: 200px;
  padding-right: 22px;
}
:deep(.el-upload-list) {
  display: flex;
  // width: 100%;
  flex-wrap: wrap;
}
.EDcenter {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 10px;
}
.text_name {
  width: 60px;
  text-align: left;
  color: #000;
  font-size: 14px;
}
</style>
